package cn.tohsaka.factory.dockercraft.Handlers;

import cn.tohsaka.factory.dockerclient.UtilsK;
import cn.tohsaka.factory.dockerclient.beans.formatScriptTmpl;
import cn.tohsaka.factory.dockercraft.Engines.veEngine;
import cn.tohsaka.factory.dockercraft.Engines.webbitWrapper;
import cn.tohsaka.factory.dockercraft.Structs.Instance;
import cn.tohsaka.factory.dockercraft.Structs.Users;
import cn.tohsaka.factory.dockercraft.Utils;
import cn.tohsaka.factory.dockercraft.Webutils.wUser;
import cn.tohsaka.factory.dockercraft.utils.*;
import cn.tohsaka.factory.eoh.interfaces.DBRequester;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang.ObjectUtils;
import org.apache.velocity.VelocityContext;
import org.webbitserver.*;
import org.webbitserver.handler.StaticFileHandler;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by Xmsoft on 2017/8/3.
 */
public class defaultHttpRequestHandler extends HttpHandlerEx {
    public veEngine v=new veEngine("www/tmpl");
    public defaultHttpRequestHandler(){
        webbitWrapper.webServer
                .add(new sessions())
                .add("/dockerapi_auth",new DockerAuthProvider())
                .add("^(\\/install\\/.+)",new installerHandler())
                .add(new StaticFileHandler("www"))
                .add("^(\\/User\\/.+)",new wUser())
                .add(this);
        prepareWebSocketConnectionEventHandler();
    }
    public void prepareWebSocketConnectionEventHandler(){
        webbitWrapper.wse.events.add(new WebSocketEvents());
        webbitWrapper.wse.events.add(new InstanceWsHandler());
    }
    @Override
    public void onRequest(HttpRequest req, session session, HttpResponse res, HttpControl rec) {
        if(sessions.get(req).get("uid")==null){
            res.status(302).header("location","/").end();
            return;
        }
        if(req.uri().equalsIgnoreCase("/dashbroad")){
            res.content(new diskutils().getFileContent(new File(System.getProperty("user.dir")+File.separator+"www/dashbroad.html"))).end();
            return;
        }
        if(req.uri().contains("/ws/")){
            rec.upgradeToWebSocketConnection(webbitWrapper.wse);
            return;
        }
        if(req.uri().contains("/instance/settings/")){
            String uuid=req.uri().replace("/instance/settings/","");
            Instance inst=new DBRequester<Instance>(Instance.class).get(String.format("SELECT * FROM dc_instances WHERE uuid='%s'",uuid.trim()));
            if(inst==null){
                send404(res);
                return;
            }
            VelocityContext ctx = new VelocityContext();
            ctx.put("servers",inst.getDocker().jarlist);
            ctx.put("serversJson", Utils.toJson(inst.getDocker().jarlist));
            ctx.put("options",inst.startOptions);
            res.content(v.execute("settings.html",ctx)).end();
            return;
        }
        if(req.uri().contains("/api/users/create")){
            String un = req.postParam("un");
            String pwd = req.postParam("pwd");

            if(( un == null || un == "" ) || (pwd == null || pwd == "")) {
                Map<String, String> result = new HashMap<String, String>();
                result.put("error", "901");
                result.put("msg", "缺少必要参数");
                res.content(Utils.toJson(result)).end();
                return;
            }
            if(Users.existsUser(un)){
                Map<String,String> result = new HashMap<String ,String>();
                result.put("error","102");
                result.put("msg","用户已存在");
                res.content(Utils.toJson(result)).end();
                return;
            }
            Users users =  Users.createUser(un,pwd);
            if(users.uid > 0){
                Map<String,String> result = new HashMap<String ,String>();
                result.put("error","0");
                result.put("msg","成功");
                result.put("data",Integer.toString(users.uid));
                res.content(Utils.toJson(result)).end();
                return;
            }else{
                Map<String,String> result = new HashMap<String ,String>();
                result.put("error","101");
                result.put("msg","用户创建失败");
                res.content(Utils.toJson(result)).end();
                return;
            }

        }
        res.status(403).end();
    }
    public void send404(HttpResponse res){
        res.status(404).content(UtilsK.INSTANCE.getFileContent(new File("www/404.html"))).end();
    }
}
